import React, {useRef, useState} from 'react';
import axios from 'axios'
import {Link} from "react-router-dom";

//https://api.github.com/search/users?q=r&sort=stars
function Search(props) {
    const userRef = useRef()
    const [userList,setUserList] = useState([])
    const [isLoading,setIsLoading] = useState(false)
    let timer = null
    const searchUsers = function (){
        if(timer)clearTimeout(timer)
        timer = setTimeout(async ()=>{
            const q = userRef.current.value.trim()
            if(!q)return alert('请输入内容！')
            setIsLoading(true)
            const {data:{items}} = await axios.get(`https://api.github.com/search/users?q=${q}&sort=stars`)
            console.log(items)
            setUserList(items)
            setIsLoading(false)
        },500)
    }
    return (
        <div>
            <h3>请输入您要搜索的用户</h3>
            <input onInput={searchUsers} ref={userRef} type="text"/>
            {
                isLoading? <h3>正在玩命加载中......</h3>:
                    userList.map(user=>(<p key={user.id}><Link to={`/details/${user.login}.html`}>{user.login}</Link></p>))
            }
        </div>
    );
}

export default Search;